package com.dong.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dong.handler.BusinessException;
import com.dong.response.ResultCodeEnum;
import com.dong.response.UserStatusEnum;
import com.dong.response.UserTypeEnum;
import com.dong.system.entity.Department;
import com.dong.system.entity.User;
import com.dong.system.mapper.UserMapper;
import com.dong.system.service.DepartmentService;
import com.dong.system.service.UserService;
import com.dong.system.vo.AddUserVO;
import com.dong.system.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author dongjian
 * @since 2021-01-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public IPage<User> findUserPage(UserVO userVO,Integer currentPage, Integer size) {
        return this.lambdaQuery()
                .eq(!ObjectUtils.isEmpty(userVO.getDepartmentId()),User::getDepartmentId, userVO.getDepartmentId())
                .eq(StringUtils.isNotBlank(userVO.getUsername()), User::getUsername, userVO.getUsername())
                .eq(StringUtils.isNotBlank(userVO.getEmail()), User::getEmail, userVO.getEmail())
                .eq(Objects.nonNull(userVO.getSex()), User::getSex, userVO.getSex())
                .eq(StringUtils.isNotBlank(userVO.getNickName()), User::getNickname, userVO.getNickName())
                .eq(User::getDeleted, 0)
                .page( new Page<>(currentPage, size));
    }

    @Override
    public void addUser(AddUserVO addUserVO){
        // 入参校验
        @NotBlank(message = "用户名不能为空") String username = addUserVO.getUsername();
        @NotNull(message = "部门id不能为空") Long departmentId = addUserVO.getDepartmentId();
        // 判断用户是否已存在
        LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(User::getUsername, username).eq(User::getDeleted, 0);
        Integer count = this.baseMapper.selectCount(userLambdaQueryWrapper);
        if (count != 0) {
            throw new BusinessException(ResultCodeEnum.USER_EXIST_EXCEPTION,"用户已存在");
        }
        // 部门查询：根据部门id查询部门信息
        Department department = departmentService.getById(departmentId);
        if (ObjectUtils.isEmpty(department)) {
            throw new BusinessException(ResultCodeEnum.DEPARTMENT_NOT_EXIST_EXCEPTION.getCode(),
                    ResultCodeEnum.DEPARTMENT_NOT_EXIST_EXCEPTION.getMessage());
        }
        User user = new User();
        BeanUtils.copyProperties(addUserVO, user);
        // 使用security对密码进行加密
        user.setPassword(passwordEncoder.encode(addUserVO.getPassword()));
        // 盐
        String salt = UUID.randomUUID().toString().substring(0,32);
        user.setSalt(salt);
        user.setCreateTime(LocalDateTime.now());
        user.setModifiedTime(LocalDateTime.now());
        // 用户类型 默认添加的是系统普通用户
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());
        // 用户状态 默认有效
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        user.setAvatar("http://badidol.com/uploads/images/avatars/201910/24/18_1571921832_HG9E55x9NY.jpg");
        this.baseMapper.insert(user);
    }


    @Override
    public void updateStatus(Long id, int status) {
        checkUserExist(id);
        // 2.权限认证：判断是否有更新权限 todo

        // 3.更新状态
        this.lambdaUpdate().eq(User::getId, id).set(User::getStatus, status).update();
    }



    @Override
    public void deleteUserById(Long id) {
        // 1.判断要更新的用户是否存在
        checkUserExist(id);
        // 2.是否有权限删除

        // 3.删除用户(更新表deleted字段为删除状态 1:已删除)
        this.lambdaUpdate().eq(User::getId, id).set(User::getDeleted, 1).update();
    }

    @Override
    public void updateUser(AddUserVO userVO) {
        // 1.判断要更新的用户是否存在
        if (ObjectUtils.isEmpty(userVO.getId())) {
           throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR, "更新用户信息id不能为空");
        }
        @NotBlank(message = "用户名不能为空") String username = userVO.getUsername();
        @NotNull(message = "部门id不能为空") Long departmentId = userVO.getDepartmentId();
        // 判断要更新的用户是否存在
        checkUserExist(userVO.getId());
        // 部门查询：根据部门id查询部门信息
        Department department = departmentService.getById(departmentId);
        if (ObjectUtils.isEmpty(department)) {
            throw new BusinessException(ResultCodeEnum.DEPARTMENT_NOT_EXIST_EXCEPTION.getCode(),
                    ResultCodeEnum.DEPARTMENT_NOT_EXIST_EXCEPTION.getMessage());
        }
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        user.setModifiedTime(LocalDateTime.now());
        this.lambdaUpdate().update(user);
    }


    /**
     * 判断用户是否已存在
     * @param id
     */
    private void checkUserExist(Long id) {
        // 1.判断要更新的用户是否存在
        User user = this.baseMapper.selectById(id);
        if (ObjectUtils.isEmpty(user) && user.getDeleted() != 1) {
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR,"要更新状态的用户不存在");
        }
    }
}
